﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using McmWinFormsApplication1.Components;
using Polenter.Mcm;

namespace McmWinFormsApplication1
{
    /// <summary>
    ///     Broadcasts messages. In a simple scenario one message channel is enough.
    ///     In an advanced one additional message channels can be added (one for errors, one for other important messages)
    /// </summary>
    public class McmComponentContainer : ComponentContainer
    {
        public const string MessagesChannelName = "Messages";
        private bool _initialized;

        private MessageChannel _messages;

        /// <summary>
        ///     The main message channel for the application. Further channels can be added using the same pattern
        /// </summary>
        public MessageChannel Messages
        {
            get
            {
                if (_messages == null)
                {
                    _messages = new MessageChannel(MessagesChannelName);
                }
                return _messages;
            }
        }

        /// <summary>
        ///     Must be invoked in the UI thread.
        ///     Otherwise the SynchronizationContext of the UI-Thread will not be created
        ///     and no UI synchronization can be made.
        /// </summary>
        public void Initialize()
        {
            if (_initialized)
            {
                throw new InvalidOperationException("Initialize() may not be invoked more than once.");
            }
            _initialized = true;

            // Injecting components using MEF
            AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            CompositionContainer container = new CompositionContainer(catalog);
            IEnumerable<McmComponent> components = container.GetExportedValues<McmComponent>();
            foreach (McmComponent mcmComponent in components)
            {
                // each component can access other components
                mcmComponent.Components = this;

                Add(mcmComponent);
            }
        }
    }
}